# 这是 socket主模块 tcp_server 与 esp32 通信
import socket
import multiprocessing
import sys
import time
import django
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "graduate_back.settings")
django.setup()  # 在此环境下操作django=
from main.models import CarsObject
# sockets 字典
class WSGIService(object):
    def __init__(self,service_address):  # tcp初始化
        self.listen_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.listen_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        self.listen_socket.bind(service_address)
        # self.listen_socket.setblocking(False)  # 设置为非堵塞方式
        self.listen_socket.listen(128)


    def client_service(self,client_socket,client_address):
        first = True
        while True: # 等待连接命令 分配 socket
            msg = client_socket.recv(1024)
            if first:
                first = False
                # socketDict.globalSockets().set_socket(client_address[0],client_socket)
                socketdict[client_address[0]] = client_socket
                print(socketdict)
                # print('tcp_server', socketDict.globalSockets().getAll_socket())
                if not CarsObject.objects.filter(id=msg).exists():
                    car = CarsObject.objects.create(ip=client_address, id=msg, status=True)
                    car.save()
                    print("创建")
                else:
                    car = CarsObject.objects.get(id=msg)
                    print("存在")
                    car.status = True # TODO 设备状态为离线暂未实现 tcp心跳检测功能
                    car.save()
            # 缓存字典  对应的socket对象  ip:socket
            if msg and not first:
                print(msg)
                # print(bytes.fromhex().decode('utf-8'))
                send_msg = '123'
                time.sleep(1)
                client_socket.send(send_msg.encode("utf-8"))

    def sevice_forever(self):
        while True:
            try :
                client_socket,client_address = self.listen_socket.accept()
                # 多进程模型
                new_process = multiprocessing.Process(target=self.client_service,args=(client_socket,client_address))
                new_process.start()
                print(client_address, "已连接")
                client_socket.close()
            except Exception as E:
                print(E)


def main():
    service_address = ("",9090)
    a = WSGIService(service_address)
    a.sevice_forever()

if __name__ == '__main__':
    main()